/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Interfata.java
 *
 * Created on 10.01.2012, 20:11:21
 */
package interfaceAndController;

import findAntlrRules.*;


import java.awt.Color;
import java.awt.Dimension;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

import Utils.Proprietati;

/**
 *
 * @author daniel
 */
public class Interfata extends javax.swing.JFrame {

    private static final Color DEFAULT_BG_COLOR = Color.decode("#FAFBFF");
    private static final Dimension DEFAULT_SIZE = new Dimension(530, 320);

    /** Creates new form Interfata */
    public Interfata() {
        
        initComponents();
        //treePanel.add(new TreeView());
        //treeView1.loadTree(null);
        this.setName("ASTor");
        pack();

    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        incarca = new javax.swing.JButton();
        analize = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        cod = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        textAst = new javax.swing.JTextArea();
        ruleComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        gName = new javax.swing.JLabel();
        generateFisOut = new javax.swing.JButton();
        generateJar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(255, 255, 255));

        incarca.setText("Incarca Gramatica");
        incarca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                incarcaActionPerformed(evt);
            }
        });

        analize.setText("Analizeaza");
        analize.setEnabled(false);
        analize.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                analizeActionPerformed(evt);
            }
        });

        cod.setColumns(20);
        cod.setRows(5);
        jScrollPane2.setViewportView(cod);

        textAst.setColumns(20);
        textAst.setRows(5);
        jScrollPane3.setViewportView(textAst);

        ruleComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ruleComboBoxActionPerformed(evt);
            }
        });

        jLabel1.setText("Gramatica :");

        generateFisOut.setText("Genereaza fis Out");
        generateFisOut.setEnabled(false);
        generateFisOut.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateFisOutActionPerformed(evt);
            }
        });

        generateJar.setText("Genereaza jar");
        generateJar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateJarActionPerformed(evt);
            }
        });

        jLabel2.setText("Oferiri un exemplu de program:");

        jLabel3.setText("AST-ul corespunzator programului dat");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(incarca)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ruleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 182, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(analize)
                        .addGap(88, 88, 88))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(gName, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 145, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 420, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 399, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(generateJar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(generateFisOut))
                    .addComponent(jLabel3))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(analize)
                    .addComponent(incarca)
                    .addComponent(ruleComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(generateJar)
                    .addComponent(generateFisOut))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(gName, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2)))
                    .addComponent(jLabel3))
                .addGap(4, 4, 4)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void incarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_incarcaActionPerformed
    
    ruleComboBox.removeAllItems();
    final JFileChooser fc = new JFileChooser(".");
    int returnVal = fc.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        if (file.isFile()) {
            try {
                Controller.loadGrammarFile(file);
                JOptionPane.showMessageDialog(this, "Gramatica a fost incarcata!!" );
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, "Eroare la parsarea fisierului " + file.getName()
                        + "\n" + e.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
            }
            gName.setText(file.getName());
            for (int i = 0; i < Controller.orderedRuleList.size(); i++) {
                ruleComboBox.addItem(Controller.orderedRuleList.get(i));
            }
            analize.setEnabled(true);
            generateFisOut.setEnabled(true);
        }
    }
    //JOptionPane.showMessageDialog(this, Controller.strTime);
    try {
		out.append("\n\n********************\n\n"+Proprietati.grammarFile +" \n" + "\tincarca gramatica" +Controller.strTime  );
		out.flush();
	} catch (IOException e) {
		JOptionPane.showMessageDialog(this, e.getMessage());
	}
}//GEN-LAST:event_incarcaActionPerformed

private void analizeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_analizeActionPerformed
        try {
            int index = Controller.analizeInput(textAst.getText(), (AntlrRule)ruleComboBox.getSelectedItem(), cod.getText(), ruleComboBox.getSelectedIndex());
            if (index >=0){
                JOptionPane.showMessageDialog(this, "Inputul a fost parsat cu success", "Success", JOptionPane.INFORMATION_MESSAGE);
                ruleComboBox.setSelectedIndex(index);
                if( Controller.checkCoveredSubRules()){
                	JOptionPane.showMessageDialog(this, "Toate regulile gramaticii au fost acoperite prin exemple!", "Success", JOptionPane.INFORMATION_MESSAGE);
                }
                this.repaint();
            }
            else
                JOptionPane.showMessageDialog(this, "Inputul nu a fost parsat cu success", "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, "IOException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (NoSuchFieldException ex) {
            JOptionPane.showMessageDialog(this, "NoSuchFieldException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(this, "ClassNotFoundException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (NoSuchMethodException ex) {
            JOptionPane.showMessageDialog(this, "NoSuchMethodException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (InstantiationException ex) {
            JOptionPane.showMessageDialog(this, "InstantiationException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (IllegalAccessException ex) {
            JOptionPane.showMessageDialog(this, "IllegalAccessException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (IllegalArgumentException ex) {
            JOptionPane.showMessageDialog(this, "IllegalArgumentException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (InvocationTargetException ex) {
            JOptionPane.showMessageDialog(this, "InvocationTargetException : \n" + ex.getMessage(), "Eroare", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
        	JOptionPane.showMessageDialog(this, "InvocationTargetException : \n" + e.getMessage() + "\n"+e.getStackTrace(), "Eroare", JOptionPane.ERROR_MESSAGE);
        	
		}
        try {
    		out.append("\n********************\n"+"exemplu : " + cod.getText()+"\n"+Controller.strTime  );
    		out.flush();
    	} catch (IOException e) {
    		JOptionPane.showMessageDialog(this, e.getMessage());
    	}
        

}//GEN-LAST:event_analizeActionPerformed

private void ruleComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ruleComboBoxActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_ruleComboBoxActionPerformed

    private void generateFisOutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateFisOutActionPerformed
    	if( !Controller.checkCoveredSubRules()){
    		int r =JOptionPane.showConfirmDialog(this, "Atentie! Nu au fost acoperite toate regulile gramaticii prin exemple!\nContinuati?"); 
    		if (r!=JOptionPane.YES_OPTION)
        		return;
    		//JOptionPane.showMessageDialog(this, "Atentie! Nu au fost acoperite toate regulile gramaticii prin exemple!", "Atentie", JOptionPane.INFORMATION_MESSAGE);
        }
    	JFileChooser fc = new JFileChooser(".");
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showSaveDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                Controller.writeToFile(fc.getSelectedFile());
                JOptionPane.showMessageDialog(this, "Gramatica adnotata a fost generata");
            } catch (IOException ex) {
            	 JOptionPane.showMessageDialog(this, "Eroare la generarea gramaticii\n" + ex.getMessage());
            }
        }
        //JOptionPane.showMessageDialog(this, Controller.strTime);
    }//GEN-LAST:event_generateFisOutActionPerformed

    private void generateJarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateJarActionPerformed
    	if( !Controller.checkCoveredSubRules()){
    		int r =JOptionPane.showConfirmDialog(this, "Atentie! Nu au fost acoperite toate regulile gramaticii prin exemple!\nContinuati?"); 
    		if (r!=JOptionPane.YES_OPTION)
        		return;
    		//JOptionPane.showMessageDialog(this, "Atentie! Nu au fost acoperite toate regulile gramaticii prin exemple!", "Atentie", JOptionPane.INFORMATION_MESSAGE);
        }
    	JFileChooser fc = new JFileChooser(".");
         fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
         int returnVal = fc.showSaveDialog(this);
         if (returnVal == JFileChooser.APPROVE_OPTION) {
             try {
            	 Controller.generateJar(fc.getSelectedFile(),Proprietati.grammarFile.contains("SS") ? "pgm" : "start");
                 JOptionPane.showMessageDialog(this,"Jar-ul a fst generat in :" + fc.getSelectedFile().getPath());
             } catch (Exception ex) {
                 Logger.getLogger(Interfata.class.getName()).log(Level.SEVERE, null, ex);
             }
         }
        // JOptionPane.showMessageDialog(this, Controller.strTime);
    	
    }//GEN-LAST:event_generateJarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Interfata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Interfata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Interfata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Interfata.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Interfata().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton analize;
    private javax.swing.JTextArea cod;
    private javax.swing.JLabel gName;
    private javax.swing.JButton generateFisOut;
    private javax.swing.JButton generateJar;
    private javax.swing.JButton incarca;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JComboBox ruleComboBox;
    private javax.swing.JTextArea textAst;
    // End of variables declaration//GEN-END:variables
    static FileWriter fstream ;
    static BufferedWriter out;
    static {
    		 fstream=null;
			try {
				fstream = new FileWriter("logger.txt",true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    		out = new BufferedWriter(fstream);
    }
    
}
